<template>
  <div>
    <el-upload
      ref="uploadImg"
      class="avatar-uploader"
      accept=".png"
      name="file"
      :action="updateImgUrl"
      :show-file-list="false"
      :headers="{ token }"
      :multiple="false"
      :auto-upload="false"
      :on-change="onChange"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <el-button type="primary" @click="doUpload">上传图片</el-button>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { getBase64 } from '@/utils/base64'
export default {
  props: {
    updateImgUrl: {
      type: String,
      required: true,
      default: ''
    },
    orginImgUrl: {
      type: String,
      required: false,
      default: ''
    }
  }, data() {
    return {
      imageUrl: this.orginImgUrl,
      token: getToken()
    }
  },
  watch: {

  },
  methods: {
    onChange(file) {
      getBase64(file.raw).then((base64) => {
        this.imageUrl = base64
      })
    },
    refreshImg() {
      this.imageUrl = ''
      this.$refs.uploadImg.clearFiles()
    },
    beforeAvatarUpload(file) {
      const isPng = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPng) {
        this.$message.error('上传头像图片只能是 png 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPng && isLt2M
    },
    handleAvatarSuccess(response) {
      if (response.code === 200) {
        this.$message.success(response.message)
      }
    },
    doUpload() {
      this.$refs.uploadImg.submit()
    }
  }
}
</script>

<style>
.switch {
  margin: 0 20px 20px 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.detail-d {
  margin: 6px;
}

.but-group {
  width: 70px;
}

::v-deep .el-autocomplete-suggestion {
  width: auto !important;
}
</style>
